package me.frank.tman.ui.stock;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import me.frank.tman.R;
import me.frank.tman.model.StockExchangeModel;
import me.frank.tman.presenter.StockPresenter;

public class StockFragment extends Fragment {
    private static final String TAG = StockFragment.class.getSimpleName();

    private RecyclerView mStockListRv;
    private StockListAdapter mStockListAdapter;
    private StockPresenter mPresenter = StockPresenter.get();

    private TextView mHintText;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_stock, container, false);

        mHintText = root.findViewById(R.id.tv_stock_hint);
        mStockListRv = root.findViewById(R.id.rv_stock_list);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mStockListRv.setLayoutManager(layoutManager);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mStockListRv.addItemDecoration(new SpacesItemDecoration(25));
        mStockListRv.setItemAnimator(new DefaultItemAnimator());

        mStockListAdapter = new StockListAdapter();
        mStockListAdapter.setOnItemClickListener((view, record) -> {
            Log.d(TAG, "OnItemClick: " + record.toString());
            Bundle bundle = new Bundle();
            bundle.putString("stock_code", record.code);
            NavHostFragment.findNavController(this).navigate(R.id.action_to_exchange_records, bundle);
        });

        mStockListRv.setAdapter(mStockListAdapter);

        List<StockExchangeModel> exchangeModels = mPresenter.getLatestStockExchanges();
        if (exchangeModels == null || exchangeModels.size() <= 0) {
            mHintText.setVisibility(View.VISIBLE);
        } else {
            mHintText.setVisibility(View.GONE);
            mStockListAdapter.setList(exchangeModels);
        }
        return root;
    }
}